// 创建一个存储loginUser的store
export const useLoginUserStore = defineStore('loginUser', {
  state: () => {
    return {
      loginUser: useLocalStorage<LoginUser>('loginUser', {}),
    };
  },
  getters: {
    isLogin(state) {
      return 'token' in state.loginUser && 'user' in state.loginUser;
    },
  },
  actions: {
    login(loginUser: LoginUser) {
      this.loginUser = loginUser;
    },
    logout() {
      this.loginUser = {};
    },
  },
});
// 创建一个存储notification信息的store
export const useNotificationStore = defineStore('notification', {
  state: () => {
    return {
      items: [] as Notice[],
    };
  },
  actions: {
    addNotice(notice: Notice) {
      this.items.push(notice);

      setTimeout(
        () => {
          this.removeNotice(notice.id);
        },
        notice.duration ? notice.duration : 3000,
      );
    },
    removeNotice(id: number) {
      this.items = this.items.filter((item) => item.id !== id);
    },
  },
});
// 创建一个存储购物车信息的store
export const useCartStore = defineStore('cart', {
  state: () => {
    return {
      items: useLocalStorage<CartItem[]>('cart', []),
    };
  },
  getters: {
    //总数量
    totalCount: (state) => {
      return state.items.reduce((a, b) => a + b.count, 0);
    },
    // 总价格
    totalPrice: (state) => {
      return state.items.reduce((a, b) => a + b.price * b.count, 0);
    },
  },
  actions: {
    // 添加购物车
    addItem(product: Product, count: number) {
      if (count <= 0) return;
      const cartItem = this.items.find((item) => item.id === product.id);

      if (cartItem) {
        const newCount = cartItem.count + count;
        cartItem.count = newCount >= cartItem.stock ? cartItem.stock : newCount;
      } else {
        count = count >= product.stock ? product.stock : count;
        this.items.push({ ...product, count });
      }
    },
    // 移除购物车
    removeItem(id: number) {
      this.items = this.items.filter((item) => item.id !== id);
    },
    // 清空购物车
    clearCart() {
      this.items = [];
    },
  },
});
